<template>
  <div id="addStocks">
    <el-dialog
      :modal-append-to-body="false"
      :visible.sync="addStockVisible"
      :before-close="handleClose"
      @close="close" width="85%">
      <!-- 卡片区域 -->

      <el-row :gutter="20">
        <el-col :span="11">
          <div class="grid-content bg-purple">
            <el-card>

              <el-steps style="
              margin-bottom: 20px;" :active="1" simple>
                <el-step title="填写" icon="el-icon-edit"></el-step>
                <el-step title="审核" icon="el-icon-postcard"></el-step>
                <el-step title="入库" icon="el-icon-set-up"></el-step>
              </el-steps>
              <el-form
                size="mini"
                ref="addRuleFormRef"
                :rules="addRules"
                :model="addRuleForm"
                label-width="80px"
              >
                <el-form-item label="添加方式">
                  <el-col :span="24">
                    <div class="grid-content bg-purple">
                      <el-radio border size="mini" @change="existenceChange(existence)" v-model="existence" :label="0">
                        新增去向
                      </el-radio>
                      <el-radio border size="mini" @change="existenceChange(existence)" v-model="existence" :label="1">
                        已知去向
                      </el-radio>
                    </div>
                  </el-col>
                </el-form-item>

                <!--从已知来源选择-->
                <el-form-item v-if="existence===1" label="物资去向" prop="consumerId">
                  <el-col :span="12">
                    <div class="grid-content bg-purple">
                      <el-select
                        v-if="existence===1"
                        style="width:100%;"
                        filterable
                        @change="supplerSelectChange(addRuleForm.consumerId)"
                        v-model="addRuleForm.consumerId"
                        placeholder="选择已存在去向"
                        value="">
                        <el-option
                          v-for="item in consumers"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        ></el-option>
                      </el-select>
                    </div>
                  </el-col>
                </el-form-item>

                <el-form-item label="领取类型" prop="type">
                  <el-radio-group v-model="addRuleForm.type">
                    <el-radio :size="'mini'" :label="0">政府</el-radio>
                    <el-radio :size="'mini'" :label="1">医院</el-radio>
                    <el-radio :size="'mini'" :label="2">小区</el-radio>
                    <el-radio :size="'mini'" :label="3">个人</el-radio>
                    <el-radio :size="'mini'" :label="4">其他</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="优先级" prop="type">
                  <el-radio-group v-model="addRuleForm.priority">
                    <el-radio :size="'mini'" :label="1">不急</el-radio>
                    <el-radio :size="'mini'" :label="2">常规</el-radio>
                    <el-radio :size="'mini'" :label="3">紧急</el-radio>
                    <el-radio :size="'mini'" :label="4">特急</el-radio>
                    <el-radio :size="'mini'" :label="5">超急</el-radio>
                  </el-radio-group>
                </el-form-item>

                <!--新增来源-->
                <div v-if="existence===0">
                  <el-row>
                    <el-col :span="8">
                      <div class="grid-content bg-purple"></div>
                      <el-form-item label="省份" prop="valueProvince">
                        <el-select
                          v-model="addRuleForm.valueProvince"
                          placeholder="请选择省"
                          @change="changeProvince"
                          value="">
                          <el-option
                            v-for="item in provinceList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <div class="grid-content bg-purple-light">
                        <el-form-item label="城市" prop="valueCity">
                          <el-select
                            v-model="addRuleForm.valueCity"
                            placeholder="请选择市"
                            @change="changeCity"
                            value="">
                            <el-option
                              v-for="item in cityOptions"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <div class="grid-content bg-purple">
                        <el-form-item label="区县" prop="valueOrigin">
                          <el-select
                            v-model="addRuleForm.valueOrigin"
                            placeholder="请选择区"
                            @change="changeOrigin"
                            value="">
                            <el-option
                              v-for="item in originOptions"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </div>
                    </el-col>
                  </el-row>
                  <el-form-item label="具体来源" prop="name">
                    <el-input placeholder="请输入具体去向" v-model="addRuleForm.name"></el-input>
                  </el-form-item>
                  <el-form-item label="联系人" prop="contact">
                    <el-input placeholder="请输入联系人名称" v-model="addRuleForm.contact"></el-input>
                  </el-form-item>
                  <el-form-item label="电话" prop="phone">
                    <el-input placeholder="请输入电话号码" v-model="addRuleForm.phone"></el-input>
                  </el-form-item>
                  <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="addRuleForm.sort" :min="1" :max="10" label="排序"></el-input-number>
                  </el-form-item>
                </div>

                <!--已知来源的详细-->
                <div v-if="existence===1">
                  <el-card class="box-card" style="margin-bottom: 30px;">
                    <div class="text item" style="font-size: 12px;padding: 5px;">
                      物资名称: <span style="margin-left: 100px;color: #999">
                    <el-tag size="mini" type="info">{{consumerInfo.name}}</el-tag>
                  </span>
                    </div>
                    <div class="text item" style="font-size: 12px;padding: 5px;">
                      物资地址: <span style="margin-left: 100px;color: #999">
                    <el-tag size="mini" type="info">{{consumerInfo.address}}
                    </el-tag></span>
                    </div>
                    <div class="text item" style="font-size: 12px;padding: 5px;">
                      联系方式: <span style="margin-left: 100px;color: #999">
                    <el-tag size="mini" type="info">{{consumerInfo.phone}}
                    </el-tag></span>
                    </div>
                    <div class="text item" style="font-size: 12px;padding: 5px;">
                      联系人员: <span style="margin-left: 100px;color: #999">
                    <el-tag size="mini" type="info">{{consumerInfo.contact}}
                    </el-tag></span>
                    </div>
                  </el-card>
                </div>

                <el-row>
                  <el-col :span="12">
                    <div class="grid-content bg-purple">
                      <el-form-item label="物资明细">
                        <el-button size="mini" plain icon="el-icon-search" @click="drawer = true">出库明细</el-button>
                      </el-form-item>
                    </div>
                  </el-col>

                  <el-col :span="12">
                    <div class="grid-content bg-purple">
                      <el-form-item label="物资总类">
                        <el-input-number v-model="itemNum" :disabled="true"></el-input-number>
                      </el-form-item>
                    </div>
                  </el-col>
                </el-row>

                <el-form-item label="描述信息" prop="remark">
                  <el-input type="textarea" :rows="2" v-model="addRuleForm.remark"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="add">立即创建</el-button>
                  <el-button @click="reset">重置</el-button>
                </el-form-item>
              </el-form>

            </el-card>
          </div>
        </el-col>

        <!--选择物资-->
        <el-col :span="13">
          <div class="grid-content bg-purple-light">
            <el-card>
              <!-- 查询搜索 -->
              <el-form :inline="true" :model="queryMap" class="demo-form-inline">
                <el-form-item label="分类">
                  <el-cascader
                    @change="selectChange"
                    v-model="categoryKeys"
                    :props="selectProps"
                    :options="catetorys"
                    clearable
                  ></el-cascader>
                </el-form-item>
                <el-form-item>
                  <el-form-item label="名称">
                    <el-input clearable="" v-model="queryMap.name" placeholder="名称" @clear="search"></el-input>
                  </el-form-item>
                  <el-button type="primary" @click="search">查询</el-button>
                </el-form-item>
              </el-form>
              <el-alert
                title="勾选先下方物资后,在左侧表单的明细中添加其出库数量"
                type="info"
                show-icon style="margin-bottom:20px;">
              </el-alert>
              <!-- 入库预选表格 -->
              <el-table
                style="height:430px;"
                :data="tableData"
                :row-key="getRowKey"
                ref="dataTable"
                @selection-change="handleSelectionChange"
                border
              >
                <el-table-column type="selection" :reserve-selection="true"></el-table-column>
                <el-table-column prop="imageUrl" label="图片" align="center" width="100px" padding="0px">
                  <template slot-scope="scope">
                    <el-popover placement="right" trigger="hover">
                      <el-image :src="scope.row.imageUrl" style="width: 200px;height: 200px">
                        <div slot="error" class="image-slot">
                          <i class="el-icon-picture-outline"></i>
                        </div>
                      </el-image>
                      <el-image slot="reference" :src="scope.row.imageUrl" :alt="scope.row.imageUrl"
                                style="height: 32px;width: 32px;cursor: pointer">
                        <div slot="error" class="image-slot">
                          <i class="el-icon-picture-outline"></i>
                        </div>
                      </el-image>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="名称"></el-table-column>
                <el-table-column prop="pnum" label="商品编号" :show-overflow-tooltip='true'></el-table-column>
                <el-table-column prop="model" label="型号"></el-table-column>
                <el-table-column prop="unit" label="单位"></el-table-column>
                <el-table-column prop="stock" label="库存"></el-table-column>
              </el-table>
              <!-- 表格分页 -->
              <el-pagination
                background
                style="margin-top:10px;"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="current"
                :page-sizes="[6, 8, 16, 20]"
                :page-size="size"
                layout="total, sizes, prev, pager, next"
                :total="total"
              ></el-pagination>


              <!-- 抽屉 -->
              <el-drawer size="49%" title="出库明细"
                         :append-to-body="true"
                         :visible.sync="drawer"
                         :modal="false"
                         :with-header="false">
              <span>
                  <el-button size="mini" style="float: right;margin: 10px;" type="primary" icon="el-icon-remove"
                             :disabled="products.length===0" @click="removeAllItem">清空
                  </el-button>
                <el-table height="700" :data="products" border>
                  <el-table-column prop="name" label="名称" width="120px;"></el-table-column>
                  <el-table-column
                    prop="imageUrl"
                    label="图片"
                    align="center"
                    width="100px"
                    padding="0px"
                  >
                    <template slot-scope="scope">
                      <el-image :src="scope.row.imageUrl" style="width: 30px;height: 30px">
                        <div slot="error" class="image-slot">
                          <i class="el-icon-picture-outline"></i>
                        </div>
                      </el-image>
                    </template>
                  </el-table-column>
                  <el-table-column prop="model" label="型号" width="100px;"></el-table-column>
                  <el-table-column label="数量" width="160">
                    <template slot-scope="scope">
                      <el-input-number
                        size="mini"
                        @change="outStockNumberChange(scope.row.number,scope.row.stock)"
                        v-model="scope.row.number"
                        :min="0"
                        :max="scope.row.stock"
                        label="描述文字"
                      ></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column prop="unit" label="单位" width="80px;"></el-table-column>
                  <el-table-column label="操作" width="100px;" fixed="right">
                    <template slot-scope="scope">
                      <el-button
                        type="danger"
                        size="mini"
                        plain
                        icon="el-icon-remove"
                        @click="removeItem(scope.row.id)"
                      >移除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </span>
              </el-drawer>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
  import { findOutEnableStocks, getProductList } from '@/api/biz/product'
  import { getCategory } from '@/api/biz/productCategory'
  import { getProvinces } from '@/api/biz/suppliers'
  import { addOutStock } from '@/api/biz/outStocks'
  import { getAllConsumerList } from '@/api/biz/consumer'

  export default {
    props: {
      addVisible: {
        type: Boolean,
        default: false
      },
    },

    data () {
      const checkEmail = (rule, value, callback) => {
        const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
        if (!value) {
          return callback(new Error('邮箱不能为空'))
        }
        setTimeout(() => {
          if (mailReg.test(value)) {
            callback()
          } else {
            callback(new Error('请输入正确的邮箱格式'))
          }
        }, 100)
      }
      var checkPhone = (rule, value, callback) => {
        const phoneReg = /^1[34578]\d{9}$$/
        if (!value) {
          return callback(new Error('电话号码不能为空'))
        }
        setTimeout(() => {
          // Number.isInteger是es6验证数字是否为整数的方法,实际输入的数字总是识别成字符串
          // 所以在前面加了一个+实现隐式转换

          if (!Number.isInteger(+value)) {
            callback(new Error('请输入数字值'))
          } else {
            if (phoneReg.test(value)) {
              callback()
            } else {
              callback(new Error('电话号码格式不正确'))
            }
          }
        }, 100)
      }
      return {
        consumerInfo: {
          name: '选择后显示具体信息',
          address: '选择后显示地址信息',
          contact: '选择后显示联系人信息',
          phone: '选择后显示联系方式',
          email: '选择后显示邮箱信息'
        },//卡片展示
        provinceList: [], // 省列表
        cityList: [], // 市列表
        originList: [], // 区列表
        cityOptions: [], // 市下拉框数据
        originOptions: [], // 区下拉框数据,
        existence: 0,
        addRules: {
          consumerId: [
            {
              required: true,
              message: '请选中物资来源',
              trigger: 'blur'
            }
          ],
          type: [{
            required: true,
            message: '请选中入库类型',
            trigger: 'blur'
          }],
          remark: [
            {
              required: true,
              message: '请输入商品说明备注',
              trigger: 'blur'
            },
            {
              min: 5,
              max: 20,
              message: '长度在 5 到 20 个字符',
              trigger: 'blur'
            }
          ],
          name: [
            {
              required: true,
              message: '请输入来源名称',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 50,
              message: '长度在 2 到 50 个字符',
              trigger: 'blur'
            }
          ],
          address: [
            {
              required: true,
              message: '请输入地址信息',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 12,
              message: '长度在 2 到 12 个字符',
              trigger: 'blur'
            }
          ],
          valueProvince: [
            {
              required: true,
              message: '请输入省份',
              trigger: 'blur'
            }
          ],
          valueCity: [{
            required: true,
            message: '请输入城市',
            trigger: 'blur'
          }],
          valueOrigin: [
            {
              required: true,
              message: '请输入区县',
              trigger: 'blur'
            }
          ],
          sort: [
            {
              required: true,
              message: '请输入排序号',
              trigger: 'blur'
            }
          ],
          contact: [{
            required: true,
            message: '请输入联系人',
            trigger: 'blur'
          }],
          phone: [
            {
              required: true,
              message: '请输入联系方式',
              validator: checkPhone,
              trigger: 'blur'
            }
          ]
        }, //添加验证
        itemNum: 0,
        addRuleForm: { type: 1 },
        consumers: [],
        categoryKeys: [],
        selectProps: {
          expandTrigger: 'hover',
          value: 'id',
          label: 'name',
          children: 'children',
          checkStrictly: false,
          multiple: true,
          emitPath: false
        }, //级联选择器配置项
        catetorys: [],
        addStockVisible: false,//添加入库弹窗
        drawer: false,
        size: 6,
        total: 100,
        current: 1,
        queryMap: {
          //可入库的物品
          status: 0,
        },
        tableData: [],
        products: [],
      }
    },
    watch: {
      // 监听 addOrUpdateVisible 改变
      addVisible () {
        this.addStockVisible = this.addVisible
      },
    },
    methods: {
      close () {
        //this.reset()
        this.$emit('changeShow', 'false')
      },

      //重置信息
      reset () {
        this.addRuleForm = { type: 1 }
        if(this.$refs['addRuleFormRef']){
        this.$nextTick(()=>{
              this.$refs.addRuleFormRef.resetFields();
               
        })
        this.consumerInfo = {
              name: '选择后显示具体信息',
              address: '选择后显示地址信息',
              contact: '选择后显示联系人信息',
              phone: '选择后显示联系方式',
        }
      }else{
        this.consumerInfo = {
              name: '选择后显示具体信息',
              address: '选择后显示地址信息',
              contact: '选择后显示联系人信息',
              phone: '选择后显示联系方式',
        }
        return;
      }
      },
      //改变来源选择
      supplerSelectChange (consumerId) {
        this.consumerInfo = this.consumers.find(function (x) {
          return x.id === consumerId
        })
      },
      /**
       * 改变来源
       */
      existenceChange (existence) {
        //选择已经存在的来源
        if (existence === 1) {
        } else if (existence === 0) {
          this.addRuleForm.consumerId = ''
        }

      if(this.$refs['addRuleFormRef']){
        this.$nextTick(()=>{
              this.$refs.addRuleFormRef.resetFields();
               
        })
        this.consumerInfo = {
              name: '选择后显示具体信息',
              address: '选择后显示地址信息',
              contact: '选择后显示联系人信息',
              phone: '选择后显示联系方式',
        }
      }else{
        this.consumerInfo = {
              name: '选择后显示具体信息',
              address: '选择后显示地址信息',
              contact: '选择后显示联系人信息',
              phone: '选择后显示联系方式',
        }
        return;
      }

        
       
      },
      /**
       * 创建入库单
       */
      //添加
      add () {
        this.$refs.addRuleFormRef.validate(async valid => {
          if (valid) {
            this.addRuleForm.address =
              this.addRuleForm.province +
              '/' +
              this.addRuleForm.city +
              '/' +
              this.addRuleForm.origin
            const car = []
            this.products.forEach(row => {
              if (row.number !== undefined) {
                const item = {
                  pnum: row.pnum,
                  productNumber: row.number
                }
                car.push(item)
              }
            })
            if (car.length > 0) {
              this.addRuleForm.products = car
            } else {
              return this.$message('入库商品的数量不能为空，请勾选物资后在明细中添加数量')
            }
            const res = await this.$confirm('此操作将提交入库单, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              })
            })
            if (res === 'confirm') {
              const res = await addOutStock(this.addRuleForm)
              if (res.code === 200) {
                this.$message('物资入库进入审核状态')
                this.close()
              }
            }
          }
        })
      },
      /**
       * 加载商品列表(可出库库)
       */
      loadTableData () {
        findOutEnableStocks(this.current, this.size, this.queryMap).then(res => {
          if (res.code === 200) {
            this.total = res.data.total
            this.tableData = res.data.records
            
          }
        })
      },
      //物品出库数量上限
      outStockNumberChange (currentValue, stock) {
        if (currentValue >= stock) {
          this.$message.warning('已达到可申请发放该物资数量的阈值')
        }
      },
      /**
       * 分类搜索改变时
       */
      selectChange () {
        let str = ''
        for (let i = 0; i < this.categoryKeys.length; i++) {
          str += this.categoryKeys[i] + ','
        }
        str = str.substring(0, str.length - 1)
        this.queryMap.categoryKeys = str
      },
      /**
       * 加载物资类别
       */
      getCategory () {
        getCategory().then(res => {
          if (res) {
            this.catetorys = this.deleteNullChildren(res.data.menus)
          }
        })
      },

      //删除children为null的菜单的children属性
      deleteNullChildren (category) {
        for (let i = 0; i < category.length; i++) {
          if (category[i].children.length > 0) {						//判断children的数组长度
            this.deleteNullChildren(category[i].children)
          }
          if (category[i].children.length === 0) {
            category[i].children = undefined
          }
        }
        return category
      },

      /**加载来源数据
       */
      getConsumers () {
        getAllConsumerList().then(res => {
          if (res.code === 200) {
            this.consumers = res.records
          }
        })
      },

      /**
       * 搜索
       */
      search () {
        this.current = 1
        this.loadTableData()
      },
      /**
       *  指定一个key标识这一行的数据
       */
      getRowKey (row) {
        return row.id
      },
      /**
       * val表示选中的表格行数据
       */
      handleSelectionChange (val) {
        console.log(val)
        this.products = val
        this.itemNum = val.length
      },
      /**
       * 改变页码
       */
      handleSizeChange (newSize) {
        this.size = newSize
        this.loadTableData()
      },
      /**
       * 点击分页
       */
      handleCurrentChange (current) {
        this.current = current
        this.loadTableData()
      },
      /**
       * 清空所有
       */
      removeAllItem () {
        this.products.forEach(row => {
          this.$refs.dataTable.toggleRowSelection(row, false)
        })
        this.products = []
      },

      /**
       * 移除item从抽屉中
       */
      removeItem (val) {
        this.products.forEach(row => {
          if (row.id === val) {
            this.$refs.dataTable.toggleRowSelection(row, false)
          }
        })
        this.products = this.products.filter(item => item.id !== val)
      },
      // 选择省
      changeProvince (val) {
        this.provinceList.forEach((province) => {
          if (val.toString() === province.value) {
            this.cityOptions = province.children
            this.originOptions = []
            this.addRuleForm.valueCity = undefined
            this.addRuleForm.valueOrigin = undefined
            //set value
            this.addRuleForm.province = province.label + '-' + province.value
          }
        })
      },
      // 选择市
      changeCity (val) {
        this.cityList.forEach((city) => {
          if (val.toString() === city.value) {
            this.originOptions = city.children
            this.addRuleForm.valueOrigin = undefined
            //set value
            this.addRuleForm.city = city.label + '-' + city.value
          }
        })
      },
      // 选择区
      changeOrigin (val) {
        this.originList.forEach((origin) => {
          if (val.toString() === origin.value) {
            //set value
            this.addRuleForm.origin = origin.label + '-' + origin.value
          }
        })
        //添加this.$forceUpdate();进行强制渲染，效果实现。搜索资料得出结果：因为数据层次太多，render函数没有自动更新，需手动强制刷新。
        this.$forceUpdate()
      },

      _getJsonData () {
        getProvinces().then(res => {
          console.log(res);
          if (res) {
            this.provinceList = []
            this.cityList = []
            this.originList = []
            res.forEach(item => {
              if (item.value.match(/0000$/)) {
                this.provinceList.push({
                  value: item.value,
                  label: item.name,
                  children: []
                })
              } else if (item.value.match(/00$/)) {
                this.cityList.push({
                  value: item.value,
                  label: item.name,
                  parent: item.parent,
                  children: []
                })
              } else {
                this.originList.push({
                  value: item.value,
                  label: item.name,
                  parent: item.parent
                })
              }
            })
            this.provinceList.forEach((province) => {
              this.cityList.forEach((city) => {
                if (province.value === city.parent) {
                  province.children.push(city)
                }
              })
            })
            this.cityList.forEach((city) => {
              this.originList.forEach((origin) => {
                if (city.value === origin.parent) {
                  city.children.push(origin)
                }
              })
            })
          }
        })
      },
      handleClose (done) {
        this.$confirm('还有未保存的工作哦确定关闭吗？')
          .then(_ => {
            done()
          })
          .catch(_ => {
          })
      }
    },
    created () {
      this.loadTableData()
      this.getCategory()
      this.getConsumers()
      this._getJsonData()
      this.reset()
    }
  }
</script>
